<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Console extends MY_Controller {

    /**
     * 页面通用数据源
     * 存储session数据变量
     * @var Array 
     */
    protected $data;

    function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
        $this->data['page_title'] = '博讯尚品后台管理系统';
        $this->data['class'] = $this->router->fetch_class();
        $this->data['method'] = $this->router->fetch_method();
        $this->data['admin_account'] = $this->session->userdata('admin_account');
        $this->data['admin_id'] = $this->session->userdata('uid');
        $this->data['admin_role'] = $this->session->userdata('admin_role');
        $this->data['admin_profile'] = $this->session->userdata('admin_profile');
        $this->data['admin_public'] = $this->session->userdata('admin_public');
    }

    /**
     * 判断当前用户是否为超级管理员身份
     */
    private function isAdmin() {
        if ($this->data['admin_role'] != 1) {
            show_404();
            exit();
        }
    }

    /**
     * 后台主页
     */
    public function dashboard() {
        $this->load->view('/admin/tmpl/_head', $this->data);
        $this->load->view('/admin/console/dashboard');
        $this->load->view('/admin/tmpl/_foot');
    }

    /**
     * 站点设置
     */
    public function website() {
        $this->data['page_title'] = '站点设置';
        $this->load->view('/admin/tmpl/_head', $this->data);
        $this->load->view('/admin/console/website');
        $this->load->view('/admin/tmpl/_foot');
    }

    /**
     * 头像上传
     */
    public function upload() {
        //图片上传配置
        $config['upload_path'] = './uploads/profile/';
        $config['allowed_types'] = 'gif|jpg|jpge|png';
        $config['file_name'] = time() . mt_rand(100, 999);
        $this->load->library('upload');
        $this->upload->initialize($config);
        if (!$this->upload->do_upload('uploadFile')) {
            echoFail();
        } else {
            $data = $this->upload->data();
            $profileSrc = '/uploads/profile/' . $data['file_name'];
            $this->db->where('id', $this->data['admin_id']);
            $this->db->update('admin', array('admin_profile' => $profileSrc));
            //更新session
            $this->session->set_userdata('admin_profile', $profileSrc);
            echoMsg(1, $data['file_name']);
        }
    }

    /**
     * 修改用户名
     */
    public function updateWebsite() {
        $data['admin_account'] = $this->input->post('name');
        $this->db->where('id', $this->data['admin_id']);
        $ret = $this->db->update('admin', $data);
        if ($ret) {
            $this->session->set_userdata('admin_account', $data['admin_account']);
            echoSuccess();
        } else {
            echoFail();
        }
    }

    /**
     * 公众号设置
     */
    public function publicNo() {
        $this->data['page_title'] = '公众号设置';

        $this->load->model('PublicModel');

        $this->data['info'] = $this->PublicModel->getPublicInfo($this->data['admin_id']);
        $this->load->view('/admin/tmpl/_head', $this->data);
        $this->load->view('/admin/console/publicNo');
        $this->load->view('/admin/tmpl/_foot');
    }

    /**
     * 公众号上传二维码
     */
    public function uploadQrcode() {
        $config['upload_path'] = './uploads/qrcode/';
        $config['allowed_types'] = 'gif|jpg|jpge|png';
        $config['file_name'] = time() . mt_rand(100, 999);
        $this->load->library('upload');
        $this->upload->initialize($config);
        if (!$this->upload->do_upload('uploadFile')) {
            echoFail();
        } else {
            $data = $this->upload->data();
            echoMsg(1, $data['file_name']);
        }
    }

    /**
     * 公众号设置
     * 修改||新增
     */
    public function publicSave() {
        $this->load->model('PublicModel');
        //表单验证
        $this->form_validation->set_rules('qrcode', '二维码', 'required');
        $this->form_validation->set_rules('name', '名称', 'trim|required');
        $this->form_validation->set_rules('number', '微信号', 'trim|required');
        $this->form_validation->set_rules('type', '类型', 'required');
        $this->form_validation->set_rules('desc', '描述', 'trim|required|min_length[5]|max_length[10]');
        $this->form_validation->set_rules('phone', '联系电话', 'trim|required|min_length[8]|max_length[11]');
        $this->form_validation->set_rules('email', '联系邮箱', 'trim|required|valid_email');

        if ($this->form_validation->run() === FALSE) {
            redirect('/console/publicNo/ret');
        } else {
            $data['uid'] = $this->data['admin_id'];
            $data['qrcode'] = $this->input->post('qrcode');
            $data['name'] = $this->input->post('name');
            $data['number'] = $this->input->post('number');
            $data['type'] = $this->input->post('type');
            $data['desc'] = $this->input->post('desc');
            $data['phone'] = $this->input->post('phone');
            $data['email'] = $this->input->post('email');
            $this->PublicModel->initPublic($data);
            $this->session->set_userdata('admin_public', $data['name']);
            redirect('/console/publicNo');
        }
    }

    /**
     * 门店列表
     */
    public function shopList() {
        $this->data['page_title'] = '门店管理';
        $this->load->view('/admin/tmpl/_head', $this->data);
        $this->load->view('/admin/console/shopList');
        $this->load->view('/admin/tmpl/_foot');
    }

    /**
     * 关闭门店
     */
    public function shopClose() {
        $id = $this->input->post('id');
        $this->db->where('id', $id);
        $ret = $this->db->update('wechat_shop', array('shop_status' => 0));
        $ret == TRUE ? echoSuccess() : echoFail();
    }

    /**
     * ajax获取当前公众号门店总数
     * 返回数据如下:
     * {"ret_code":51,"ret_msg":""}
     */
    public function ajaxGetShopRows() {
        $this->load->model('ShopModel');
        $this->load->model('PublicModel');
        $tmp = $this->PublicModel->getPublicInfo($this->data['admin_id']);
        echoMsg($this->ShopModel->getShopCountById($tmp['id']));
    }

    /**
     * ajax获取当前页数据
     * 返回JSON数据
     * ID,名称,密匙,状态,入驻时间
     */
    public function ajaxGetShopListData() {
        $this->load->model('ShopModel');
        $this->load->model('PublicModel');
        $current_page = $this->input->post('current_page'); // 当前页
        $page_size = 10; // 每页显示10条数据
        $offset = $current_page * $page_size; // 偏移量

        $tmp = $this->PublicModel->getPublicInfo($this->data['admin_id']);
        $sql = "SELECT id , shop_name , shop_auth , shop_status , FROM_UNIXTIME(shop_create_time,'%Y-%m-%d %H:%i:%S') as time FROM wechat_shop WHERE shop_public_id =" . $tmp['id'] . " ORDER BY id ASC LIMIT $offset , $page_size";
        $query = $this->db->query($sql);
        echoJson($query->result_array());
    }

    /**
     * 新增门店
     */
    public function shopCreate() {

        $this->data['page_title'] = '门店管理';
        $this->load->model('ShopModel');
        $this->load->model('PublicModel');
        $tmp = $this->PublicModel->getPublicInfo($this->data['admin_id']);
        if (!$tmp['id']) {
            // 还未设置公众号信息
            $this->data['is_set_public'] = FALSE;
        } else {
            $this->data['is_set_public'] = TRUE;
        }

        $this->form_validation->set_rules('shop_name', '名称', 'trim|required');
        $this->form_validation->set_rules('shop_desc', '介绍', 'trim|required');
        $this->form_validation->set_rules('shop_address', '地址', 'trim|required');
        $this->form_validation->set_rules('shop_province', '省份', 'required');
        $this->form_validation->set_rules('shop_city', '城市', 'required');
        $this->form_validation->set_rules('shop_phone', '电话', 'trim|required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('/admin/tmpl/_head', $this->data);
            $this->load->view('/admin/console/shopCreate');
            $this->load->view('/admin/tmpl/_foot');
        } else {
            $data['id'] = 0;
            $data['shop_img_0'] = $this->input->post('shop_img_0');
            $data['shop_img_1'] = $this->input->post('shop_img_1');
            $data['shop_img_2'] = $this->input->post('shop_img_2');
            $data['shop_img_3'] = $this->input->post('shop_img_3');
            $data['shop_name'] = $this->input->post('shop_name');
            $data['shop_desc'] = $this->input->post('shop_desc');
            $data['shop_phone'] = $this->input->post('shop_phone');
            $data['shop_province'] = $this->input->post('shop_province');
            $data['shop_city'] = $this->input->post('shop_city');
            $data['shop_address'] = $this->input->post('shop_address');
            $data['shop_public_id'] = $tmp['id'];
            $data['shop_admin_id'] = $this->data['admin_id'];
            $this->ShopModel->initShop($data);
            redirect('/console/shopList');
        }
    }

    /**
     * 修改门店
     */
    public function shopEdit($id = NULL) {
        $this->data['page_title'] = '门店修改';
        $this->load->model('ShopModel');
        $this->data['detail'] = $this->ShopModel->getShopDetailById($id);

        $this->form_validation->set_rules('shop_name', '名称', 'trim|required');
        $this->form_validation->set_rules('shop_desc', '介绍', 'trim|required');
        $this->form_validation->set_rules('shop_address', '地址', 'trim|required');
        $this->form_validation->set_rules('shop_province', '省份', 'required');
        $this->form_validation->set_rules('shop_city', '城市', 'required');
        $this->form_validation->set_rules('shop_phone', '电话', 'trim|required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('/admin/tmpl/_head', $this->data);
            $this->load->view('/admin/console/shopEdit');
            $this->load->view('/admin/tmpl/_foot');
        } else {
            $data['id'] = $this->input->post('id');
            $data['shop_img_0'] = $this->input->post('shop_img_0');
            $data['shop_img_1'] = $this->input->post('shop_img_1');
            $data['shop_img_2'] = $this->input->post('shop_img_2');
            $data['shop_img_3'] = $this->input->post('shop_img_3');
            $data['shop_name'] = $this->input->post('shop_name');
            $data['shop_desc'] = $this->input->post('shop_desc');
            $data['shop_phone'] = $this->input->post('shop_phone');
            $data['shop_province'] = $this->input->post('shop_province');
            $data['shop_city'] = $this->input->post('shop_city');
            $data['shop_address'] = $this->input->post('shop_address');
            $this->ShopModel->initShop($data);
            redirect('/console/shopList');
        }
    }

    /**
     * 门店上传图片
     */
    public function shopUpload() {
        $config['upload_path'] = './uploads/shop/';
        $config['allowed_types'] = 'gif|jpg|jpge|png';
        $config['file_name'] = time() . mt_rand(100, 999);
        $this->load->library('upload');
        $this->upload->initialize($config);
        if (!$this->upload->do_upload('uploadFile')) {
            echoFail();
        } else {
            $data = $this->upload->data();
            echoMsg(1, $data['file_name']);
        }
    }

    /**
     * 分店管理跳转控制器
     * @param type $shop_id
     */
    public function branche($shop_id) {
        $this->db->where('shop_id', $shop_id);
        $query = $this->db->get('wechat_shop_branche');
        $has_branche = $query->num_rows();
        if ($has_branche == 0) {
            // 不存在分店,跳转至分店新增页面
            redirect('/console/brancheCreate');
        } else {
            // 存在分店,跳转至分店修改页面
            redirect("/console/brancheList/$shop_id");
        }
    }

    /**
     * 分店列表
     */
    public function brancheList($shop_id) {
        $this->data['page_title'] = '分店管理';

        $this->db->where('id', $shop_id);
        $shop_query = $this->db->get('wechat_shop');
        $this->data['shop_detail'] = $shop_query->row_array();

        $this->db->where('shop_id', $shop_id);
        $branche_query = $this->db->get('wechat_shop_branche');
        $this->data['detail'] = $branche_query->result_array();

        $this->load->view('/admin/tmpl/_head', $this->data);
        $this->load->view('/admin/console/brancheList');
        $this->load->view('/admin/tmpl/_foot');
    }

    /**
     * 分店管理
     */
    public function brancheCreate() {
        $this->data['page_title'] = '新增分店';

        $this->form_validation->set_rules('shop_id', '门店ID', 'trim|required');
        $this->form_validation->set_rules('branche_address', '地址', 'trim|required');
        $this->form_validation->set_rules('branche_province', '省份', 'required');
        $this->form_validation->set_rules('branche_city', '城市', 'required');
        $this->form_validation->set_rules('branche_phone', '电话', 'trim|required');
        $this->form_validation->set_rules('branche_name', '分店名称', 'trim|required');

        $this->load->model('ShopModel');
        $this->load->model('PublicModel');
        $tmp = $this->PublicModel->getPublicInfo($this->data['admin_id']);
        $this->data['detail'] = $this->ShopModel->getShopListById($tmp['id']);

        if ($this->form_validation->run() === FALSE) {
            $this->data['is_success'] = 0;
        } else {
            $this->data['is_success'] = 1;
            $this->load->model('BrancheModel');
            $data['shop_id'] = $this->input->post('shop_id');
            $data['branche_province'] = $this->input->post('branche_province');
            $data['branche_city'] = $this->input->post('branche_city');
            $data['branche_address'] = $this->input->post('branche_address');
            $data['branche_phone'] = $this->input->post('branche_phone');
            $data['branche_name'] = $this->input->post('branche_name');
            $data['id'] = 0;

            $this->BrancheModel->initBranche($data);
        }

        $this->load->view('/admin/tmpl/_head', $this->data);
        $this->load->view('/admin/console/brancheCreate');
        $this->load->view('/admin/tmpl/_foot');
    }

    /**
     * 分店信息修改
     * @param type $shop_id 门店ID
     * @param type $branche_id 分店ID
     */
    public function brancheEdit($shop_id = NULL, $branche_id = NULL) {
        $this->data['page_title'] = '分店修改';

        $this->db->where('id', $shop_id);
        $shop_query = $this->db->get('wechat_shop');
        $this->data['shop_detail'] = $shop_query->row_array();

        $this->db->where('id', $branche_id);
        $branche_query = $this->db->get('wechat_shop_branche');
        $this->data['detail'] = $branche_query->row_array();

        $this->form_validation->set_rules('branche_address', '地址', 'trim|required');
        $this->form_validation->set_rules('branche_province', '省份', 'required');
        $this->form_validation->set_rules('branche_city', '城市', 'required');
        $this->form_validation->set_rules('branche_phone', '电话', 'trim|required');
        $this->form_validation->set_rules('branche_name', '分店名称', 'trim|required');

        if ($this->form_validation->run() === FALSE) {
            $this->data['shop_id'] = $shop_id;
            $this->data['branche_id'] = $branche_id;
            $this->load->view('/admin/tmpl/_head', $this->data);
            $this->load->view('/admin/console/brancheEdit');
            $this->load->view('/admin/tmpl/_foot');
        } else {
            $this->load->model('BrancheModel');
            $data['branche_province'] = $this->input->post('branche_province');
            $data['branche_city'] = $this->input->post('branche_city');
            $data['branche_address'] = $this->input->post('branche_address');
            $data['branche_phone'] = $this->input->post('branche_phone');
            $data['branche_name'] = $this->input->post('branche_name');
            $data['id'] = $this->input->post('branche_id');

            $this->BrancheModel->initBranche($data);
            redirect('/console/brancheList/' . $this->input->post('shop_id'));
        }
    }

    /**
     * 绑定记录
     */
    public function shop_admin() {
        $this->data['page_title'] = '绑定记录';
        $this->load->view('/admin/tmpl/_head', $this->data);
        $this->load->view('/admin/console/shop_admin');
        $this->load->view('/admin/tmpl/_foot');
    }

    public function debug() {
        $sql = " SELECT * FROM wechat_coupon c,wechat_public p,wechat_shop s "
                . " WHERE (c.public_id = p.id) AND "
                . " (c.shop_id = s.id) AND "
                . " (p.id = 1) ";
        $data = $this->db->query($sql);
        header('content-type:text/html;chareset=utf-8');
        var_dump($data->result_array());
    }

    /**
     * 优惠券
     */
    public function coupon() {
        $this->data['page_title'] = '优惠券管理';

        $this->load->model('ShopModel');
        $this->load->model('PublicModel');
        $this->load->model('CouponModel');

        $tmp = $this->PublicModel->getPublicInfo($this->data['admin_id']);
        $shop_data = $this->ShopModel->getShopListById($tmp['id']); // 查询门店信息

        $this->data['list'] = $this->CouponModel->getCouponListById($tmp['id']);    // 优惠券列表数据
        $this->data['create'] = $shop_data;    //制作优惠券所需门店数据

        $this->load->view('/admin/tmpl/_head', $this->data);
        $this->load->view('/admin/console/coupon');
        $this->load->view('/admin/tmpl/_foot');
    }

    /**
     * ajax load 分店地址等信息
     */
    public function ajaxLoadBranche() {
        $shop_id = $this->input->post('shop_id');
        $this->load->model('BrancheModel');
        $data = $this->BrancheModel->getBrancheListById($shop_id);
        echoJson($data);
    }

    /**
     * ajax 新增门店信息
     */
    public function ajaxCreateCoupon() {
        $data = array(
            'id' => 0,
            'shop_id' => $this->input->post('shop_id'),
            'branche_id' => $this->input->post('branche_id'),
            'coupon_info' => $this->input->post('info'),
            'coupon_rule' => $this->input->post('rule'),
            'coupon_count' => $this->input->post('count'),
            'coupon_start' => strtotime($this->input->post('start')),
            'coupon_end' => strtotime($this->input->post('end')),
        );
        $this->load->model('CouponModel');
        $this->load->model('PublicModel');
        $tmp = $this->PublicModel->getPublicInfo($this->data['admin_id']);
        $data['public_id'] = $tmp['id'];
        $ret = $this->CouponModel->initCoupon($data);
        $ret === TRUE ? echoSuccess() : echoFail();
    }

    /**
     * 优惠券修改
     */
    public function couponEdit($id = NULL) {
        $this->data['page_title'] = '优惠券修改';

        $this->load->model('ShopModel');
        $this->load->model('PublicModel');

        $tmp = $this->PublicModel->getPublicInfo($this->data['admin_id']);
        $shop_data = $this->ShopModel->getShopListById($tmp['id']); // 查询门店信息

        $this->data['shop'] = $shop_data; //门店数据
        $query = $this->db->get_where('wechat_coupon', array('id' => $id));
        $this->data['coupon'] = $query->row_array(); //优惠券信息

        $this->load->view('/admin/tmpl/_head', $this->data);
        $this->load->view('/admin/console/couponEdit');
        $this->load->view('/admin/tmpl/_foot');
    }

    public function ajaxEditCoupon() {
        $data = array(
            'id' => $this->input->post('id'),
            'shop_id' => $this->input->post('shop_id'),
            'branche_id' => $this->input->post('branche_id'),
            'coupon_info' => $this->input->post('info'),
            'coupon_rule' => $this->input->post('rule'),
            'coupon_count' => $this->input->post('count'),
            'coupon_start' => strtotime($this->input->post('start')),
            'coupon_end' => strtotime($this->input->post('end')),
        );
        $this->load->model('CouponModel');
        $this->load->model('PublicModel');
        $tmp = $this->PublicModel->getPublicInfo($this->data['admin_id']);
        $data['public_id'] = $tmp['id'];
        $ret = $this->CouponModel->initCoupon($data);
        $ret === TRUE ? echoSuccess() : echoFail();
    }

    /**
     * 优惠券删除
     */
    public function ajaxCouponDel() {
        $id = $this->input->post('id');
        $this->db->where('id', $id);
        $ret = $this->db->delete('wechat_coupon');
        $ret === TRUE ? echoSuccess() : echoFail();
    }

    /* ---------------------------超级管理员--------------------------- */

    /**
     * 幻灯片
     */
    public function banner() {
        $this->isAdmin();

        $this->data['page_title'] = '幻灯片设置';

        $this->load->model('BannerModel');
        $list = $this->BannerModel->getBannerList();
        $this->data['list'] = $list;

        $this->load->view('/admin/tmpl/_head', $this->data);
        $this->load->view('/admin/console/banner');
        $this->load->view('/admin/tmpl/_foot');
    }

    /**
     * 新增幻灯片
     */
    public function ajaxCreateBanner() {
        $this->isAdmin();
        $data = array(
            'id' => 0,
            'banner_img_url' => $this->input->post('src'),
            'banner_redirect_url' => $this->input->post('url'),
            'banner_is_show' => $this->input->post('show'),
            'banner_create_time' => time(),
        );
        $this->load->model('BannerModel');
        $ret = $this->BannerModel->initBanner($data);
        $ret === TRUE ? echoSuccess() : echoFail();
    }

    /**
     * 幻灯片图片上传
     */
    public function bannerUpload() {
        $this->isAdmin();
        $config['upload_path'] = './uploads/banner/';
        $config['allowed_types'] = 'gif|jpg|jpge|png';
        $config['file_name'] = time() . mt_rand(100, 999);
        $this->load->library('upload');
        $this->upload->initialize($config);
        if (!$this->upload->do_upload('uploadFile')) {
            echoFail();
        } else {
            $data = $this->upload->data();
            echoMsg(1, $data['file_name']);
        }
    }

    /**
     * 幻灯片删除
     */
    public function ajaxDelBanner() {
        $this->isAdmin();
        $this->db->where('id', $this->input->post('id'));
        $ret = $this->db->delete('wechat_banner');
        $ret === TRUE ? echoSuccess() : echoFail();
    }

    /**
     * 修改幻灯片
     * @param type $id
     */
    public function bannerEdit($id=FALSE) {
        $this->isAdmin();
        $ret = $this->db->get_where('wechat_banner', array('id' => $id));
        $this->data['detail'] = $ret->row_array();

        $this->form_validation->set_rules('banner_img_url', '图片', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('/admin/tmpl/_head', $this->data);
            $this->load->view('/admin/console/bannerEdit');
            $this->load->view('/admin/tmpl/_foot');
        } else {
            $data['id'] = $this->input->post('id');
            $data['banner_img_url'] = $this->input->post('banner_img_url');
            $data['banner_redirect_url'] = $this->input->post('banner_redirect_url');
            $data['banner_is_show'] = $this->input->post('show');
            $this->load->model('BannerModel');
            $this->BannerModel->initBanner($data);
            redirect('/console/banner');
        }
    }

}
